package br.com.stepmail;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{

	public static final String SENDER_ID = "626572062744";
	public static final String TAG = "gcm";
	public static final String IP = "http://www.stepmail.com.br/besouro/WSBesouro/WSAcesso.asmx";
	
	@Override
	protected void onRegistered(Context context,final String redId) {
		Log.d(TAG, "OnRegistered(regId): " + redId);
		/*new Thread(){
			public void run(){
				sendRegistrationToServer(redId);
			};
		}.start();*/
		
	}
	
	@Override
	protected void onUnregistered(Context context, String regId) {
		Log.d(TAG, "onUnregistered(regId): " + regId);
		
	}
	
	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.d(TAG, "onMessage");
		
		Bundle extras = intent.getExtras();
		/*extras.getString("mensagem");
		extras.getString("titulo");*/
		
		PendingIntent pit = PendingIntent.getActivity(context,0, new Intent(), 0);
		
		Notification notificao = new NotificationCompat.Builder(context)
														.setTicker("StepMail new message")
														.setContentTitle(extras.getString("titulo"))
																		.setContentIntent(pit) // Cuidado que pode dar erro aqui...
																		.setContentText(extras.getString("mensagem"))
																		.setSmallIcon(R.drawable.stepmailicon)
																		.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
																		.setAutoCancel(true)
																		.setNumber(extras.getInt("badge"))
																		.build();
		
		NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		manager.notify(1, notificao);
		
	}
	
	@Override
	protected void onError(Context context, String errorId) {
		Log.d(TAG, "onError: " + errorId);
		
	}

	public void sendRegistrationToServer(String registrationId){
		
		final String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.stepmail.com.br/besouro/WSBesouro/WSAcesso.asmx/InserirDispositivo");
		
		try{
			
			JSONObject obj = new JSONObject();
			obj.put("guidCodigoAcesso", "qualquerId");
			obj.put("idDevice", deviceId);
			
			
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	
	
	
}
